package com.peaw.exception;

import org.springframework.core.NestedCheckedException;

/**
 * <pre>
 * <b></b>
 *
 * </pre>
 * 
 * @author MrLiberte
 * @version 1.0.0 [2016年4月14日]
 */
public class PeawException extends NestedCheckedException implements MessageAble {

	private static final long serialVersionUID = 1277054113069147599L;
	
	public PeawException(){
		super("");
		messageSupport = new MessageSupport();
	}

	public PeawException(String msg) {
		super(msg);
		messageSupport = new MessageSupport();
		messageSupport.setMessageKey(msg);
	}
	
	public PeawException(String msg, Object args[]) {
		super(msg);
		messageSupport = new MessageSupport();
		messageSupport.setMessageKey(msg);
		messageSupport.setArgs(args);
	}
	
	public PeawException(String msg, Throwable throwable) {
		super(msg, throwable);
		messageSupport = new MessageSupport();
		messageSupport.setMessageKey(msg);
	}
	
	public PeawException(String msg, Throwable throwable, Object args[])
    {
        super(msg, throwable);
        messageSupport = new MessageSupport();
        messageSupport.setMessageKey(msg);
        messageSupport.setArgs(args);
    }
	
    public PeawException(Throwable throwable)
    {
        super("", throwable);
        messageSupport = new MessageSupport();
    }

	@Override
	public String getDefaultMessage() {
        String s = messageSupport.getDefaultMessage();
        if(s == null)
        {
            StringBuffer stringbuffer = (new StringBuffer(getClass().getName())).append(" MessageCode: ").append(getMessageKey());
            if(messageSupport.getArgs() != null)
            {
                stringbuffer.append(" Args: ");
                Object aobj[] = messageSupport.getArgs();
                for(int i = 0; i < aobj.length; i++)
                    stringbuffer.append(aobj[i]).append(" ");

            }
            if(getCause() != null)
            {
                stringbuffer.append(" nested exception is: ");
                stringbuffer.append(getCause());
            }
            return stringbuffer.toString();
        } else
        {
            return s;
        }
	}

	@Override
	public String getMessageKey() {
		return messageSupport.getMessageKey();
	}

	@Override
	public Object[] getArgs() {
		return messageSupport.getArgs();
	}
	
    public String toString()
    {
        StringBuffer stringbuffer = new StringBuffer(super.toString());
        if(messageSupport.getArgs() != null)
        {
            stringbuffer.append(" Args:");
            Object aobj[] = messageSupport.getArgs();
            for(int i = 0; i < aobj.length; i++)
                stringbuffer.append(aobj[i]).append(" ");

        }
        return stringbuffer.toString();
    }
    
	protected MessageSupport messageSupport;
	
}
